package cn.hx.admin.service.impl;

import cn.hx.admin.dao.MenuDao;
import cn.hx.admin.dao.UserDao;
import cn.hx.admin.entity.Menu;
import cn.hx.admin.entity.User;
import cn.hx.admin.entity.UserAuthority;
import cn.hx.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-12-07 15:02:44
 */
@Service("userService")
public class UserServiceImpl implements UserService, UserDetailsService {
    @Resource
    private UserDao userDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userId) {
        return this.userDao.queryById(userId);
    }

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @return 查询结果
     */
    @Override
    public List<User> queryByPage(User user) {
        return this.userDao.queryAll(user);
    }

    @Override
    public List<User> queryByDeptAndUserSign(User user) {
        return this.userDao.queryByDeptAndUserSign(user);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (StringUtils.hasText(password)) {
            user.setPassword(passwordEncoder.encode(password));
        }
        user.setDelFlag("0");
        user.setStatus("0");
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (StringUtils.hasText(password)) {
            user.setPassword(passwordEncoder.encode(password));
        }
        this.userDao.update(user);
        return this.queryById(user.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userDao.deleteById(userId) > 0;
    }

    /**
     * User批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public Boolean deleteUserByIdsBatch(String ids) {
        List<Integer> idList = new ArrayList<>();
        String[] split = ids.split(",");
        for (String s : split) {
            idList.add(Integer.valueOf(s));
        }
        return this.userDao.deleteUserIdsByBatch(idList);
    }

    @Autowired
    private MenuDao menuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.loadUserByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名或者密码错误");
        }
        Integer roleId = user.getRoleId();
        List<Menu> menus;
        //roleId为1表示超级管理员，超级管理员不需要授权，理应拥有所有权限
        if (roleId == 1) {
            menus = menuDao.queryAll(null);
        } else {
            menus = menuDao.queryByRoleId(roleId);
        }

        Set<UserAuthority> collect = menus.stream()
                .map(o -> {
                    return new UserAuthority().setAuthority(o.getPerms());
                })
                .filter(o -> StringUtils.hasText(o.getAuthority())).collect(Collectors.toSet());

        //设置权限信息 Set
        //of 快速创建 Set
        user.setAuthorities(collect);
        //模拟数据库获取数据后设置角色和资源

        return user;
    }
}
